package controller

import (
	"pro-downloader/app/model"
	"pro-downloader/app/utils"
	"github.com/gin-gonic/gin"
	"gopkg.in/go-playground/validator.v8"
	"net/http"
)

var cookieKey = "simon_token"
var domain = utils.GetDomain()

func Index(ctx *gin.Context) {
	name,_ := ctx.Request.Cookie(cookieKey)
	hostname := ctx.Request.Host
	if hostname == "" {
		hostname = domain
	}
	ctx.HTML(http.StatusOK, "index.html", gin.H{"username":name.Value,"hostname": hostname})
}

func Login(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "login.html", gin.H{"hostname": ctx.Request.Host})
}

func LoginDo(ctx *gin.Context)  {
	user := model.User{}
	if err := ctx.ShouldBind(&user); err != nil {
		ctx.JSON(http.StatusOK, gin.H{"code": 10, "msg": user.GetError(err.(validator.ValidationErrors))})
		return
	}

	if user.Name == "simon" && user.Pwd == "qwe123" {
		//添加cookie
		ctx.SetCookie(cookieKey,"simon",  3600, "/", ctx.Request.Host, false, true)
		ctx.JSON(http.StatusOK, gin.H{"code": 0, "msg":"登录成功", "url":"/"})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"code": 20, "msg":"登录失败"})
}

func Exit(ctx *gin.Context) {
	//清除cookie
	ctx.SetCookie(cookieKey,"nothing", -1, "/",ctx.Request.Host, false, true)
	ctx.Redirect(http.StatusTemporaryRedirect, "/login")
}
